package com.kmzx.one.common.utils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;

public class WXCloudUtils {

    private final static Logger logger = LoggerFactory.getLogger(WXCloudUtils.class);


    public final static int connectTimeout = 30000;
    public final static int longConnectTimeout = 50000;


    private static PoolingHttpClientConnectionManager connManager = null;
    private static CloseableHttpClient httpclient = null;

    static {
        connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(50);
        httpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .setConnectionManager(connManager).build();

        // Create socket configuration
        SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        connManager.setDefaultSocketConfig(socketConfig);
        // Create message constraints
        MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
        // Create connection configuration
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
                .setMessageConstraints(messageConstraints).build();
        connManager.setDefaultConnectionConfig(connectionConfig);
        // 总最大连接数
        connManager.setMaxTotal(600);
        // 每个host的最大连接数
        connManager.setDefaultMaxPerRoute(10);
    }


    public static int checkIPisTencentCloundUser(String ip) {
        if (ip != null) {
            if (!"".equals(ip)) {
                if (!ip.equals("127.0.0.1")) {
                    RequestConfig requestConfig = RequestConfig.custom()
                            .setSocketTimeout(connectTimeout)
                            .setConnectTimeout(connectTimeout)
                            .setConnectionRequestTimeout(connectTimeout)
                            .build();
                    String noDecodeUrl = "https://a.tool.lu/__tm.gif?domain=tool.lu&url=https://tool.lu/ip/&title=IP地址查询 - 在线工具&referrer=&sh=1440&sw=2560&cd=24&lang=zh-CN";
                    String reqUrl = "https://a.tool.lu/__tm.gif?domain=tool.lu&url=https%3A%2F%2Ftool.lu%2Fip%2F&title=IP%E5%9C%B0%E5%9D%80%E6%9F%A5%E8%AF%A2%20-%20%E5%9C%A8%E7%BA%BF%E5%B7%A5%E5%85%B7&referrer=&sh=1440&sw=2560&cd=24&lang=zh-CN";

                    String ipWhereUrl = "https://tool.lu/ip/ajax.html";

                    HttpGet get = new HttpGet(reqUrl);
                    get.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
                    get.setHeader("Referer", "https://tool.lu/");
                    get.setConfig(requestConfig);

                    String uuid = "";
                    String _access = "";
                    int responseCode = -1;
                    boolean ok = false;
                    CloseableHttpResponse response = null;
                    try {
                        response = httpclient.execute(get);
                        try {
                            responseCode = response.getStatusLine().getStatusCode();
                            Header[] allHeaders = response.getAllHeaders();
                            for (Header oneHeader : allHeaders) {
                                String name = oneHeader.getName();
                                String value = oneHeader.getValue();
                                if ("Set-Cookie".equals(name)) {
                                    if (value.startsWith("uuid")) {
                                        uuid = value;
                                    } else if (value.startsWith("_access")) {
                                        _access = value;
                                        ok = true;
                                    }
                                }
                            }
                        } catch (Exception e) {
                            logger.error("请求地址:{},异常,原因:{}", noDecodeUrl, e.getMessage());
                        } finally {
                            if (response != null) {
                                response.close();
                            }
                        }


                        HttpPost httpPost = new HttpPost(ipWhereUrl);
                        httpPost.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
                        httpPost.setHeader("Referer", "https://tool.lu/ip/");
                        httpPost.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
                        httpPost.setHeader("accept", "application/json, text/javascript, */*; q=0.01");
                        httpPost.setHeader("Cookie", uuid + ";" + _access + ";");

                        // 填充请求体
                        httpPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("ip", ip)), Consts.UTF_8));

                        httpPost.setConfig(requestConfig);


                        response = httpclient.execute(httpPost);
                        try {
                            // 执行POST请求
                            HttpEntity entity = response.getEntity(); // 获取响应实体
                            try {
                                if (null != entity) {
                                    String responseContent = EntityUtils.toString(entity, Consts.UTF_8);
                                    if (responseContent != null && !"".equals(responseContent)) {

                                        logger.info("请求ip地址校验返回数据:{}",responseContent);
                                        responseContent = StringEscapeUtils.unescapeJava(responseContent);
                                        logger.info("解密,请求ip地址校验返回数据:{}",responseContent);
                                        if (responseContent.contains("腾讯云")) {
                                            return 2;
                                        }
                                    }
                                }
                            } finally {
                                if (entity != null) {
                                    entity.getContent().close();
                                }
                            }
                        } finally {
                            if (response != null) {
                                response.close();
                            }
                        }
                        logger.info("请求地址:{} 响应码:{}", noDecodeUrl, responseCode);
                    } catch (SocketTimeoutException e) {
                        logger.error(String.format("Get 请求URL超时:%s", noDecodeUrl), e);
                    } catch (Exception e) {
                        logger.error(String.format("Get 请求URL出错了, URL:%s", noDecodeUrl), e);
                    } finally {
                        if (!ok) {
                            get.releaseConnection();
                        }
                    }

                    return 0;
                } else {
                    return -1;
                }
            } else {
                return -1;
            }
        } else {
            return -1;
        }

    }
}
